package org.oka.camsa.client;

import org.oka.camsa.model.LoginInfo;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

public class CamsApp implements EntryPoint {

	private boolean datastoreDumped = false;
	private LoginInfo loginInfo = null;
	private Viewport viewport;

	private static native void redirect(String url) /*-{ $wnd.location = url; }-*/;

	public boolean isDatastoreDumped() {
		return datastoreDumped;
	}

	public void setDatastoreDumped(boolean datastoreDumped) {
		this.datastoreDumped = datastoreDumped;
	}

	@Override
	public void onModuleLoad() {
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {
					public void onFailure(Throwable error) {
					}

					public void onSuccess(LoginInfo result) {
						loginInfo = result;
						if (loginInfo.isLoggedIn()) {
							loadCamsApp();
						} else {
							redirect(loginInfo.getLoginUrl());
						}
					}
				});
	}

	private void loadCamsApp() {

		viewport = new Viewport();
		viewport.setLayout(new BorderLayout());
		CamsAppLayout c = new CamsAppLayout(loginInfo.getLogoutUrl());
		viewport.add(c, new BorderLayoutData(LayoutRegion.CENTER));

		RootPanel.get().add(viewport);
	}
}
